package com.jlmv.poseidon.framework.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;

@SuppressWarnings("unchecked")
public abstract class AbstracDaoJPA<T> implements IDao<T> {

//	private Class<T> entityClass;

	@PersistenceContext
	private EntityManager entityManager;

	public AbstracDaoJPA() {
		super();
		// this.entityClass = (Class<T>) getEnitdad();
//		this.entityClass = (Class<T>) GenericTypeResolver.resolveTypeArgument(
//				getClass(), AbstracDaoJPA.class);
	}

	

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.casewaresa.p01f21.dao.IDao#getEntityManager()
	 */
	public EntityManager getEntityManager() {
		return entityManager;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.casewaresa.p01f21.dao.IDao#create(T)
	 */
	public T create(T entity) {
		getEntityManager().persist(entity);
		return entity;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.casewaresa.p01f21.dao.IDao#edit(T)
	 */
	public T edit(T entity) {
		getEntityManager().merge(entity);
		return entity;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.casewaresa.p01f21.dao.IDao#remove(T)
	 */
	public T remove(T entity) {
		getEntityManager().remove(getEntityManager().merge(entity));
		return entity;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.casewaresa.p01f21.dao.IDao#find(java.lang.Object)
	 */
	public T find(Class<T> entity, Object id) {
		return getEntityManager().find(entity, id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.casewaresa.p01f21.dao.IDao#findAll()
	 */
	public List<T> findAll(Class<T> entity) {
		javax.persistence.criteria.CriteriaQuery<T> cq = (CriteriaQuery<T>) getEntityManager()
				.getCriteriaBuilder().createQuery();
		cq.select(cq.from(entity));
		return getEntityManager().createQuery(cq).getResultList();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.casewaresa.p01f21.dao.IDao#findRange(int[])
	 */
	public List<T> findRange(Class<T> entity, int[] range) {
		CriteriaQuery<Object> cq = getEntityManager().getCriteriaBuilder()
				.createQuery();
		cq.select(cq.from(entity));
		javax.persistence.Query q = getEntityManager().createQuery(cq);
		q.setMaxResults(range[1] - range[0] + 1);
		q.setFirstResult(range[0]);
		return (List<T>) q.getResultList();
	}
	
	
	public List<T> find(){
	
		javax.persistence.Query q = getEntityManager().createNativeQuery("SELECT * FROM TIPO_DOCUMENTO WHERE ESTADO = 'A'");
		
		return (List<T>) q.getResultList();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.casewaresa.p01f21.dao.IDao#count()
	 */
	public int count(Class<T> entity) {
		CriteriaQuery<Object> cq = getEntityManager().getCriteriaBuilder()
				.createQuery();
		javax.persistence.criteria.Root<T> rt = cq.from(entity);
		cq.select(getEntityManager().getCriteriaBuilder().count(rt));
		javax.persistence.Query q = getEntityManager().createQuery(cq);
		return ((Long) q.getSingleResult()).intValue();
	}
}
